<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="用户名：">
        <template #prefix>
          <el-icon class="el-input__icon"><user /></el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="password" v-model="loginForm.password" placeholder="密码：" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon"><lock /></el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button :icon="CircleClose" round @click="resetForm(loginFormRef)" size="large">重置</el-button>
    <el-button :icon="UserFilled" round @click="login(loginFormRef)" size="large" type="primary" :loading="loading">
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config"; // 主页地址"/home/index"
import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus"; //通知组件
import { loginApi } from "@/api/modules/login"; //登录接口
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "js-md5";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

// 通过el-form生成一个表单实例，使用 ref 方法创建了一个响应式对象 loginFormRef，并指定了它的类型为 FormInstance
// 这样做的目的是为了在模板中能够正确地访问 ElForm 组件的实例方法和属性
type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
// 用户名和密码的验证规则
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }]
});

// loading为false表示当前不处于加载状态。这个变量可以用于在表单提交时显示 loading 状态，防止用户重复提交表单
const loading = ref(false);
// loginForm 存储用户输入的用户名和密码
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: ""
});

// login
// 接收一个参数 formEl，类型为 FormInstance | undefined
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    // 表单验证，会调用form里的rules，也就是上面定义的loginRules，如果验证不通过则直接返回
    if (!valid) return;
    loading.value = true; //表示开始加载
    try {
      // 1.执行登录接口
      const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });

      //将数据存储到store中
      userStore.setAccessToken(data.accessToken);
      userStore.setRefreshToken(data.refreshToken);
      userStore.setUserInfo({
        name: data.name,
        userAvatar: data.userAvatar,
        departmentId: data.departmentId,
        userRole: data.userRole,
        userId: data.userId,
        departmentName: data.departmentName
      });

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();

      // 4.跳转到首页
      router.push(HOME_URL);
      // 使用 ElNotification 组件显示欢迎消息
      ElNotification({
        title: getTimeState(),
        message: userStore.userInfo.name + " 欢迎登录 NEU-Logistics",
        type: "success",
        duration: 4000
      });
    } finally {
      // 无论登录流程是否成功，我们都会将 loading 变量的值设置为 false，表示加载完成
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
